package com.mmall.service.impl;

import com.mmall.common.Const;
import com.mmall.common.ServiceResponse;
import com.mmall.common.TokenCache;
import com.mmall.dao.UserMapper;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jws.soap.SOAPBinding;
import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public ServiceResponse<User> login(String username, String password) {
        System.out.println(username);
        int resultCount  = userMapper.checkUsername(username);
        if (resultCount==0){
            return ServiceResponse.createByErrorMessage("用户名不可用");
        }

        String MD5Password = MD5Util.stringMD5(password);
        User user = userMapper.selectLogin(username,MD5Password);
        if (user == null){
            return ServiceResponse.createByErrorMessage("密码错误");
        }
        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);

        return ServiceResponse.createBySuccess("登陆成功",user);
    }

    @Override
    public ServiceResponse<String> register(User user) {
        int resultCount  = userMapper.checkUsername(user.getUsername());
        if (resultCount>0){
            return ServiceResponse.createByErrorMessage("用户名已存在");
        }

        int emailCount = userMapper.checkEmail(user.getEmail());
        if (emailCount>0){
            return ServiceResponse.createByErrorMessage("邮箱已存在");
        }

        user.setPassword(MD5Util.stringMD5(user.getPassword()));
        user.setRole(Const.Role.ROLE_CUSTOMER);

        int insert = userMapper.insert(user);

        if (insert==0){
            return ServiceResponse.createByErrorMessage("注册失败");
        }

        return ServiceResponse.createBySuccessMessage("注册成功");
    }

    public ServiceResponse selectQuestion(String username){
        String userQuestion = userMapper.selectQuestionByUsername(username);
        if (!StringUtils.isNotBlank(userQuestion)){
            return ServiceResponse.createByErrorMessage("该用户未设置密码问题");
        }else {
            return ServiceResponse.createBySuccess(userQuestion);
        }
    }

    public ServiceResponse<String> checkAnswer(String username,String question,String answer){
        int i = userMapper.checkAnswer(username, question, answer);
        if (i>0){
            String forgetToken = UUID.randomUUID().toString();
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
            return ServiceResponse.createBySuccess(forgetToken);
        }else {
            return ServiceResponse.createByErrorMessage("验证问题输入错误");
        }
    }

    public ServiceResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        if (StringUtils.isBlank(forgetToken)){
            return ServiceResponse.createByErrorMessage("需要参数");
        }
        String key = TokenCache.getKey(TokenCache.TOKEN_PREFIX+ username);
        if (StringUtils.isBlank(key)){
            return ServiceResponse.createByErrorMessage("forgettoken失效");
        }

        int flag = 0;

        if (StringUtils.equals(key,forgetToken)){
            String md5password = MD5Util.stringMD5(passwordNew);
            flag= userMapper.resetPassword(username, md5password);
        }

        if (flag>0){
            return ServiceResponse.createBySuccessMessage("修改成功");
        }else {
            return ServiceResponse.createByErrorMessage("修改失败");
        }
    }

    public ServiceResponse<String> resetPassword(User user,String passwordOld,String passwordNew){
        String md5PasswordOld = MD5Util.stringMD5(passwordOld);
        int flagOldPassword = userMapper.checkOldPassword(md5PasswordOld,user.getId());
        if (flagOldPassword==0){
            return ServiceResponse.createByErrorMessage("旧密码不正确");
        }
        user.setPassword(MD5Util.stringMD5(passwordNew));
        int flagNewPassword = userMapper.updateByPrimaryKeySelective(user);
        if (flagNewPassword==0){
            return ServiceResponse.createByErrorMessage("密码修改失败");
        }
        return ServiceResponse.createBySuccessMessage("修改成功");
    }

    public ServiceResponse<User> updateInformation(User user){
        int checkFlag = userMapper.checkEmailByUserId(user.getId(), user.getEmail());
        if (!(checkFlag==0)){
            return ServiceResponse.createByErrorMessage("邮箱已存在");
        }
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag==0){
            return ServiceResponse.createByErrorMessage("用户更新失败");
        }
        return ServiceResponse.createBySuccess(user);
    }

    public ServiceResponse<User> getInformation(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if (user==null){
            return ServiceResponse.createByErrorMessage("用户不存在");
        }
        user.setPassword(StringUtils.EMPTY);
        return ServiceResponse.createBySuccess(user);
    }

    /**
     * 判断是否为管理员
     * @param user
     * @return
     */
    public ServiceResponse checkAdminRole(User user){
        if (user != null && user.getRole() == Const.Role.ROLE_ADMIN){
            return ServiceResponse.createBySuccess();
        }else {
            return ServiceResponse.createByError();
        }
    }


}
